//
// Copyright (C) Microsoft. All rights reserved.  
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not 
// use this file except in compliance with the License.  You may obtain a copy 
// of the License at http://www.apache.org/licenses/LICENSE-2.0  
// 
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
// MERCHANTABLITY OR NON-INFRINGEMENT. 
//
// See the Apache License, Version 2.0 for specific language governing 
// permissions and limitations under the License.
//
//
#include "common_mesh.hlsli"

P2F main(V2PLit pixel)
{
    P2F result;

    float d = dot(pixel.worldNorm, pixel.toEye);
    if (d < 0) pixel.worldNorm *= -1;

    // compute amount of ambient light
    float4 ambient = AmbientLight * MaterialAmbient;

    // source color used for diffuse lighting
    float4 sourceColor = pixel.diffuse;
    
    // compute amount of contribution per light
    float3 worldNorm = normalize(pixel.worldNorm);
    float diffuseAmount = saturate(dot(LightDirection[0], worldNorm));

    float4 diffuse = diffuseAmount * LightColor[0] * sourceColor;

    // compute specular contribution
    float3 vHalf = normalize(LightDirection[0] + normalize(pixel.toEye));
    float specularAmount = saturate(dot(worldNorm, vHalf));
    specularAmount = pow(specularAmount, max(MaterialSpecularPower,0.0001f)) * LightSpecularIntensity[0];
    float4 specular = MaterialSpecular * LightColor[0] * specularAmount;
    specular.a = 0.0f;

    // set fragment final color
    result.fragment.rgb = saturate(ambient + diffuse).rgb;
    result.fragment.a = pixel.diffuse.a;
    if (d >= 0)
    {
        result.fragment *= Texture1.Sample(TextureSampler, pixel.uv);
    }
    else
    {
        result.fragment *= float4(1, 1, 1, 1);
    }
    result.fragment = saturate(result.fragment + specular);
    if (result.fragment.a == 0.0f) discard;

    return result;
}